
/*
 * 2016-9-12 巫瑜
 * 阅片UI界面交互事件处理
 *
 *
 * */

(function (lmViewer,_,$) {
  var RT = lmViewer.RT;
  if (!RT) throw  "the lmViewer.RT is not exist!!";
  var DoseGridFrame = RT.DoseGridFrame= {
    data:{
      doseGridlist:new Array(),
      doseGridConf:{
        alpha: 128,
        colorMap:0,
        filename:"1d4b4135-6126-4caf-87dc-dfee552f1ec0",
        index:120,
        range_min:"min",
        range_max:"max",
        position:{
          left:50,
          top:50
        },
        scale:1
      },
    },
    fn:{
      srv:{
        serveIP:lm.environment("RTlocalserver").hostUrl,
        // serveIP:"http://192.168.100.113:9000",
        // serveIP:"http://192.168.0.102:9000",
        // serveIP:"http://192.168.0.102:9000",
        get_doseGridFrame:function (position_z,callback) {
          var ip= DoseGridFrame.fn.srv.serveIP;
          var temp = _.find(DoseGridFrame.data.doseGridlist,function (doseGrid) {
            return doseGrid.position_z == position_z;
          });

          var url =ip+'/api/structure/dosegridframe/'+temp.DoseGridFrame;
          $.get(url,function(data){

            var  _obj= _.extend({},DoseGridFrame.data.doseGridlist[temp.index],data);
            DoseGridFrame.data.doseGridlist[temp.index] = _obj;
              callback(_obj);
          });
        },
        get_doseGridFrameList:function () {
          var ip= DoseGridFrame.fn.srv.serveIP;
          var url =ip+'/api/structure/dosegridframe';
          $.get(url,function(data){
            _.map(data,function (doseGrid,index) {
              doseGrid.position_z= doseGrid.position;
              var temp = _.extend({},DoseGridFrame.data.doseGridConf,doseGrid);
              temp.filename = doseGrid.DoseGridFrame;
              /*
              * 列表加载完成之后，加载详情页
              *
              * */
             // DoseGridFrame.fn.srv.get_doseGridFrame(temp);
              DoseGridFrame.data.doseGridlist.push(temp);
            });
            DoseGridFrame.data.doseGridlist =  _.sortBy(DoseGridFrame.data.doseGridlist,"index");
            // console.log("DoseGridFrame.data.doseGridlist:"+JSON.stringify(DoseGridFrame.data.doseGridlist,null,4))
          });
        },
      },
      file:{
        alpha: 128,
        colorMap:0,
        filename:"1d4b4135-6126-4caf-87dc-dfee552f1ec0",
        index:120,
        range_min:"min",
        range_max:"max",
        position:{
          left:50,
          top:50
        },
        scale:1
      },
      colorMapFun:function () {
                var UseColorMap;
                switch (DoseGridFrame.fn.config().colorMap){
                  case 0 :
                    UseColorMap = "Jet";
                    break;
                  case 1 :
                    UseColorMap = "Parula";
                    break;
                  case 2 :
                    UseColorMap = "HSV";
                    break;
                  case 3 :
                    UseColorMap = "Summer";
                    break;
                  case 4 :
                    UseColorMap = "Spring";
                    break;
                  case 5 :
                    UseColorMap = "Hot";
                    break;
                  case 6 :
                    UseColorMap = "Cool";
                    break;
                  case 7 :
                    UseColorMap = "Colorcube";
                    break;
                  case 8 :
                    UseColorMap = "Autumn";
                    break;
                  case 9 :
                    UseColorMap = "Winter";
                    break;
                }
                return UseColorMap;
              },
      config:function(){
                var file = DoseGridFrame.fn.file;
                var conf = {
                            alpha:file.alpha,
                            position:{
                              left:file.position.left||0,
                              top:file.position.top||0,
                            },
                            colorMap:file.colorMap,
                            range_min: file.range_min,
                            range_max: file.range_max,
                            scale: file.scale||1,
                            filename:file.filename
                }
                return conf;
      },
      /*
      *二次插值运算公式
      *
       */
      bilinear:function(srcImg, destImg, scale) {
        // c.f.: wikipedia english article on bilinear interpolation
        // taking the unit square, the inner loop looks like this
        // note: there's a function call inside the double loop to this one
        // maybe a performance killer, optimize this whole code as you need
        function inner(f00, f10, f01, f11, x, y) {
          var un_x = 1.0 - x; var un_y = 1.0 - y;
          return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
        }

        function ivect(ix, iy, w) {
          // byte array, r,g,b,a
          return((ix + w * iy) * 4);
        }

        var i, j;
        var iyv, iy0, iy1, ixv, ix0, ix1;
        var idxD, idxS00, idxS10, idxS01, idxS11;
        var dx, dy;
        var r, g, b, a;
        for (i = 0; i < destImg.height; ++i) {
          iyv = i / scale;
          iy0 = Math.floor(iyv);
          // Math.ceil can go over bounds
          iy1 = ( Math.ceil(iyv) > (srcImg.height-1) ? (srcImg.height-1) : Math.ceil(iyv) );
          for (j = 0; j < destImg.width; ++j) {
            ixv = j / scale;
            ix0 = Math.floor(ixv);
            // Math.ceil can go over bounds
            ix1 = ( Math.ceil(ixv) > (srcImg.width-1) ? (srcImg.width-1) : Math.ceil(ixv) );
            idxD = ivect(j, i, destImg.width);
            // matrix to vector indices
            idxS00 = ivect(ix0, iy0, srcImg.width);
            idxS10 = ivect(ix1, iy0, srcImg.width);
            idxS01 = ivect(ix0, iy1, srcImg.width);
            idxS11 = ivect(ix1, iy1, srcImg.width);
            // overall coordinates to unit square
            dx = ixv - ix0; dy = iyv - iy0;
            // I let the r, g, b, a on purpose for debugging
            r = inner(srcImg.data[idxS00], srcImg.data[idxS10],
              srcImg.data[idxS01], srcImg.data[idxS11], dx, dy);
            destImg.data[idxD] = r;

            g = inner(srcImg.data[idxS00+1], srcImg.data[idxS10+1],
              srcImg.data[idxS01+1], srcImg.data[idxS11+1], dx, dy);
            destImg.data[idxD+1] = g;

            b = inner(srcImg.data[idxS00+2], srcImg.data[idxS10+2],
              srcImg.data[idxS01+2], srcImg.data[idxS11+2], dx, dy);
            destImg.data[idxD+2] = b;

            a = inner(srcImg.data[idxS00+3], srcImg.data[idxS10+3],
              srcImg.data[idxS01+3], srcImg.data[idxS11+3], dx, dy);
            destImg.data[idxD+3] = a;
          }
        }
      },
      parserDefColor :function (name,alpha,colors) {
      var _colorSet = colors[name];
      var TempColorSet = _.map(_colorSet,function (point) {
        var _colorSet = _.map(point,function (color) {
          return parseInt(color*255);
        });
        _colorSet.push(parseInt(alpha*DoseGridFrame.fn.config().alpha));
        return _colorSet;
      })
      return TempColorSet;
    },
      colorSet:function () {
          var colorSetName =  DoseGridFrame.fn.colorMapFun();
        var _colorSet = DoseGridFrame.fn.parserDefColor(colorSetName,1,colorMaps);
        return _colorSet;
      },
      pixelData:function (dataGrid) {
        var config =  DoseGridFrame.fn.config();
        var colorSet =  DoseGridFrame.fn.colorSet();
        Array.prototype.max = function() { return Math.max.apply({},this) };
        Array.prototype.min = function() { return Math.min.apply({},this) };
        var min =config.range_min="min"===config.range_min?dataGrid.rawDoseGridData.min():config.range_min;
        var max = config.range_max="max"===config.range_max?dataGrid.rawDoseGridData.max():config.range_max;
        var rawDoseGridData_new = _.map(dataGrid.rawDoseGridData, function (num, i) {

          if( num<config.range_min || num>config.range_max )
          {
            num=0;
          }
          else{

          }
          var _num = Math.abs(Math.round((num - min) / (max - min) * 256));
          var point = colorSet[_num];
          if(_num==0)
          {
            point[3]=0;
          }
          return point;
        });

        dataGrid.scale = dataGrid.xPixelSpacing * config.scale;
        dataGrid.width = dataGrid.cols;
        dataGrid.height = dataGrid.rows;
        dataGrid.x = dataGrid.position[0];
        dataGrid.y = dataGrid.position[1];
        dataGrid.z = dataGrid.position[2];
        dataGrid.showHeight =Math.ceil( dataGrid.height * dataGrid.xPixelSpacing * config.scale);
        dataGrid.showWidth = Math.ceil(dataGrid.width * dataGrid.yPixelSpacing * config.scale);
        dataGrid.pixelData= rawDoseGridData_new;
        return dataGrid;
      },
      createCanvas : function (config,dataGrid) {
      var cvs = document.createElement("canvas");
      cvs.id="newCans";
      cvs.style.position= "absolute";
        var imagePosition = lmViewer.data.tags.message[0].imagePosition.split("\\")  ;
        var pixelSpacing = lmViewer.data.tags.message[0].pixelSpacing.split("\\")  ;
        var top =parseInt((dataGrid.x -parseFloat(imagePosition[0]))/parseFloat(pixelSpacing[0]))-2;
        var left =parseInt((dataGrid.y -parseFloat(imagePosition[1]))/parseFloat(pixelSpacing[1]))+44;

        cvs.style.top= top +"px";
        cvs.style.left= left + "px";
        cvs.height=dataGrid.showHeight;
        cvs.width=dataGrid.showWidth;
        return cvs;
      },
      createImage:function(dataGrid){
        var config =  DoseGridFrame.fn.config();
        var cvs  =  DoseGridFrame.fn.createCanvas(config,dataGrid);
        dataGrid = DoseGridFrame.fn.pixelData(dataGrid);
        var colorSet =  DoseGridFrame.fn.colorSet();
        dataGrid.canvasID = cvs.id;
        var cxt = cvs.getContext("2d");
        var _image = cxt.createImageData(dataGrid.cols,dataGrid.rows);
        var i=0;
        _.each(dataGrid.pixelData,function (data) {
          _.each(data,function (color) {
            _image.data[i++] = color;
          })
        });
        var new_image = cxt.createImageData(dataGrid.showWidth,dataGrid.showHeight);
        DoseGridFrame.fn.bilinear(_image,new_image,dataGrid.scale);
        cxt.putImageData(new_image,0,0);
        return cvs;
      },
      },
    ctrl:{
        init:function () {
          console.log("DoseGridFrame.fn.ctrl.init() is running...");
          DoseGridFrame.fn.srv.get_doseGridFrameList();
        },
      CreateDataGridByIndex:function (index) {
        var newCans = $("#newCans");
        if (newCans)newCans.remove();
          DoseGridFrame.data.doseGridlist[index]=DoseGridFrame.fn.pixelData(DoseGridFrame.data.doseGridlist[index]);
          var cvs = DoseGridFrame.fn.createImage(DoseGridFrame.data.doseGridlist[index]);
          return cvs;
      },


      CreateDataGridByPosition:function (position) {
        var newCans = $("#newCans");
        if (newCans)newCans.remove();

        var dataGrid = _.find(DoseGridFrame.data.doseGridlist,function (doseGrid) {
          return position == doseGrid.position[2]+doseGrid.indexValue;
        });
        if (dataGrid) {
          DoseGridFrame.data.doseGridlist[dataGrid.index]=DoseGridFrame.fn.pixelData(dataGrid);
          var cvs = DoseGridFrame.fn.createImage(DoseGridFrame.data.doseGridlist[dataGrid.index]);
          return cvs;
        }else{
          throw "not dataGrid  from CreateDataGridByPosition(postion)"
        }
      },



      AppendToDiv:function (index,DivName) {
        var that = this;
        var cvs = that.CreateDataGridByIndex(index);
       $("#"+DivName).append(cvs);
      },

      /*
      * 2016.9.26 David V1.0.1
      * 通过z轴坐标位置访问
      *
      * */

      AppendToDivByPosition:function (position,DivName) {
        var that = this;
        var cvs = that.CreateDataGridByPosition(position);
        $("#"+DivName).append(cvs);
      },


      ctrlFn:function () {
        DoseGridFrame.fn.funFn("call the fun...");
        console.log("this is  ctrl!!")
      }
    },
    ui:{},
  }
  lmViewer.RT.DoseGridFrame= DoseGridFrame;
  //lmViewer.RT.DoseGridFrame.fn.srv.get_doseGridFrameList();
  lmViewer.RT.DoseGridFrame.ctrl.init();


})(lmViewer,_,$);

// lmViewer.RT.DoseGridFrame.ctrl.ctrlFn();
